//
//  AddItemViewController.swift
//  memo
//
//  Created by fly on 2019/10/12.
//  Copyright © 2019 Xiang HongFei. All rights reserved.
//

import UIKit
import UserNotifications

protocol AddItemViewControllerDelegate: class {
    func AddItemViewController(_controller:AddItemViewController,endAdding item:TodoItem)
    func AddItemViewController(_controller:AddItemViewController,endEditing item:TodoItem)
}

class AddItemViewController: UITableViewController ,UITextFieldDelegate{
    weak var delegatr: AddItemViewControllerDelegate?

    var itemToEdit : TodoItem?
    var dueDate = Date()
    var datePickerVisible = false
    
    func showDatePicker() {
        datePickerVisible = true
        
        let indexPathDatePicker = IndexPath(row: 2, section: 1)
        tableView.insertRows(at: [indexPathDatePicker], with: .fade)
        
    }
    
    @IBOutlet weak var datePicker: UIDatePicker!
    @IBOutlet weak var datePickerCell: UITableViewCell!
    @IBOutlet weak var remindSwitch: UISwitch!
    @IBOutlet weak var dueDateLabel: UILabel!
    @IBOutlet weak var doneBarButton: UIBarButtonItem!
    @IBOutlet weak var inputTextFiled: UITextField!
    @IBAction func cancel(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    @IBAction func commit(_ sender: Any) {
        if let item = itemToEdit {
            item.text = inputTextFiled.text!
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
            item.scheduleNotification()
            delegatr?.AddItemViewController(_controller: self, endEditing: item)
        } else {
            let item = TodoItem(text: inputTextFiled.text!, checked: false)
            item.text = inputTextFiled.text!
            item.checked = false
            item.shouldRemind = remindSwitch.isOn
            item.dueDate = dueDate
            item.scheduleNotification()
            delegatr?.AddItemViewController(_controller: self, endAdding: item)
            
        }
        dismiss(animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        if let item = itemToEdit {
            title = "编辑备忘录"
            inputTextFiled.text = item.text
            remindSwitch.isOn = item.shouldRemind
            dueDate = item.dueDate
        }else{
            title = "新建备忘录"
        }
        
        updateDueDateLabel()
    }
    
    func updateDueDateLabel(){
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy年MM月dd日 HH:mm"
        dueDateLabel.text = formatter.string(from: dueDate)
    }
 
    override func viewWillAppear(_ animated: Bool) {
        super.viewDidLoad()
        inputTextFiled.becomeFirstResponder()
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let oldStr = textField.text! as NSString
        let newStr = oldStr.replacingCharacters(in: range, with: string)
        doneBarButton.isEnabled = newStr.count > 0
        
        
        return true
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 1 && indexPath.row == 2 {
            return datePickerCell
        } else {
            return super.tableView(tableView, cellForRowAt: indexPath)
        }
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 1 && datePickerVisible {
            return 3
        } else {
            return super.tableView(tableView, numberOfRowsInSection: section)
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 && indexPath.row == 2 {
            return 217
        } else {
            return super.tableView(tableView, heightForRowAt: indexPath)
        }
    }
    
    override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
        if indexPath.section == 1 && indexPath.row == 1 {
            return indexPath
        } else {
            return nil
        }
    }
    
    override func tableView(_ tableView: UITableView, indentationLevelForRowAt indexPath: IndexPath) -> Int {
        var newIndexPath = indexPath
        if indexPath.section == 1 && indexPath.row == 2 {
            newIndexPath = IndexPath(row: 0, section: indexPath.section)
        }
        return super.tableView(tableView, indentationLevelForRowAt: newIndexPath)
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        if indexPath.section == 1 && indexPath.row == 1 {
            showDatePicker()
        }
    }
    

    @IBAction func dateChange(_ sender: Any) {
        dueDate = datePicker.date
        updateDueDateLabel()
    }
    @IBAction func remindtoggled(_ sender: Any) {
        if remindSwitch.isOn {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options: [.alert,.sound]) { (_,_) in
                
            }
        }
    }
    // MARK: - Table view data source


    /*
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)

        // Configure the cell...

        return cell
    }
    */

    /*
    // Override to support conditional editing of the table view.
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the specified item to be editable.
        return true
    }
    */

    /*
    // Override to support editing the table view.
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            // Delete the row from the data source
            tableView.deleteRows(at: [indexPath], with: .fade)
        } else if editingStyle == .insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */

    /*
    // Override to support rearranging the table view.
    override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {

    }
    */

    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        // Return false if you do not want the item to be re-orderable.
        return true
    }
    */

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
